// routes/person.js 使用的中间件

// 获取用户列表
const testList = (req, res, next) => {
  // 参数验证
  // 1. 获取参数
  const { current, pagesize, is_status, gender, search } = req.query

  // 2. 参数验证
  if (!(current === undefined || !isNaN(current))) return next(5)
  if (!(pagesize === undefined || !isNaN(pagesize))) return next(5)
  if (!(is_status === undefined || is_status === 'all' || is_status - 0 === 1 || is_status - 0 === 0)) return next(5)
  if (!(gender === undefined || gender === 'all' || gender === '保密' || gender === '男' || gender === '女')) return next(5)

  // 3. 把没传递的参数给一个默认值
  if (current === undefined) req.query.current = 1
  if (pagesize === undefined) req.query.pagesize = 5
  if (is_status === undefined) req.query.is_status = 'all'
  if (gender === undefined) req.query.gender = 'all'
  if (search === undefined) req.query.search = ''

  next()
}

// 修改用户状态
const testStatus = (req, res, next) => {
  // 1. 拿到两个参数
  const { id, status } = req.body

  // 2. 验证参数
  if (id.length !== 24) return next(5)
  if (!(status === '1' || status === '0')) return next(5)

  next()
}

// 验证用户 id
const testId = (req, res, next) => {
  
  // 1. 拿到两个参数
  const id = req.params.id || req.body.id

  // 2. 验证参数
  if (id.length !== 24) return next(5)

  next()
}

// 添加用户
const testAdd = (req, res, next) => {
  // 1. 拿到用户传递来的 参数
  const { username, password, nickname } = req.body

  // 2. 非空验证(保证前端必须要传递了这个参数)
  if (!username || !password || !nickname) return next(4)

  // 3. 参数的格式验证(正则验证)
  // 暂时简单验证一个长度, 将来学完了正则, 你们自己回来补上
  if (username.length < 5 || username.length > 12 || password.length < 5 || password.length > 12 || nickname.length < 2 || nickname.length > 6) return next(5)
  next()
}

// 验证修改用户信息的参数
const testUpdate = (req, res, next) => {
  // 1. 拿到用户传递来的 参数
  const { nickname, desc, id } = req.body
  
  // 2. 非空验证(保证前端必须要传递了这个参数)
  if (!nickname || !id) return next(4)
  // 3. 参数的格式验证(正则验证)
  if (nickname.length < 2 || nickname.length > 6 || desc.length > 200 || id.length !== 24) return next(5)
  if (req.file) {
    const avatar = '/public/avatar/' +  req.file.filename
    req.body.avatar = avatar
  }
  next()
}

module.exports = {
  testList,
  testStatus,
  testId,
  testAdd,
  testUpdate,
}
